package com.yboot.starter.caffeine.core;

import com.github.benmanes.caffeine.cache.Expiry;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.nullness.qual.NonNull;

import java.util.concurrent.TimeUnit;

/**
 * 动态缓存策略
 *
 * // 配置
 * Cache<String, Object> cache = Caffeine.newBuilder()
 *     .expireAfter(new CustomExpiry())
 *     .build();
 *
 * 使用示例
 * cache.policy().expireVariably().ifPresent(e -> {
 *     e.put("order_123", orderData, 2, TimeUnit.HOURS); // 订单数据2小时后失效
 * });
 * @author yangcs
 * @date 2025/7/21
 */
public class CustomExpiry implements Expiry<String, CaffeineEntry> {
    @Override
    public long expireAfterCreate(@NonNull String s, @NonNull CaffeineEntry o, long l) {
        return o.getExpireTime();
    }

    @Override
    public long expireAfterUpdate(@NonNull String s, @NonNull CaffeineEntry o, long l, @NonNegative long l1) {
        return o.getExpireTime();
    }

    @Override
    public long expireAfterRead(@NonNull String s, @NonNull CaffeineEntry o, long l, @NonNegative long l1) {
        if (o.isAccessFresh()) {
            return o.getExpireTime();
        }
        return l1;
    }
}
